L.GroupsManager = L.Class.extend({
	includes: L.Mixin.Events,

	initialize: function(couplingOptions) {
		
		this._noteGroups = [];
		this._workGroups = [];
		this._couplingOptions = couplingOptions;
		
		if ( this._couplingOptions && this._couplingOptions.enabled )
			this._couple(this._couplingOptions);
		
	},
	
	addWorkGroup: function(name, ownerId) {
		if ( !this.groupExists(name, "work") )
			return this.addGroup(name, "work", ownerId);
	},
	
	addNoteGroup: function(name, ownerId) {
		if ( !this.groupExists(name, "note") )
			return this.addGroup(name, "note", ownerId);
	},
	
	addGroup: function(name, groupType, ownerId) {
		var group = new L.Group(name, groupType, ownerId, this._couplingOptions);
		if ( groupType == "note" )
			this._noteGroups.push(group);
		else
			this._workGroups.push(group);
		
		group.on('invitationEvent',this._handleInvitation, this);
		group.on('memberEvent', Skt.handlers.memberEventHandler, null);
		
		this.fire('groupEvent', {
			group: group,
			action: 'addGroup'
		});
		
		return group;
	},
	
	_handleInvitation: function(params) {
		Skt.groupsManager.issueInvitation(params);
	},
	
	issueInvitation: function(params) {
		if ( params.invitedId == Skt.user.id ) {
			this.fire('invitationEvent', {
				action: "issue",
				name: params.name,
				groupType: params.groupType,
				ownerId: params.ownerId,
				inviterId: params.inviterId
			});
		}
	},
	
	dismissInvitation: function(params) {
		if ( params.invitedId == Skt.user.id ) {
			this.fire('invitationEvent', {
				action: "dismiss"
			});
		}
	},
	
	getGroup: function(name, type) {
		if ( type == "note" ) {
			for ( var m = 0; m < this._noteGroups.length; ++m )
				if ( this._noteGroups[m].getName() == name )
					return this._noteGroups[m];
		} else {
			for ( var m = 0; m < this._workGroups.length; ++m )
				if ( this._workGroups[m].getName() == name )
					return this._workGroups[m];
		}
		return null;
	},
	
	groupExists: function(name, type) {
		if ( type == "note" ) {
			for ( var m = 0; m < this._noteGroups.length; ++m )
				if ( this._noteGroups[m].getName() == name )
					return true;
		} else {
			for ( var m = 0; m < this._workGroups.length; ++m )
				if ( this._workGroups[m].getName() == name )
					return true;
		}
		return false;
	},
	
	getNoteGroups: function() {
		return this._noteGroups;
	},
	
	getWorkGroups: function() {
		return this._workGroups;
	},
	
	_couple: function(couplingOptions) {
		couplingOptions.adapter.coupleObject(
			couplingOptions.carriedId, 
			this,
			{
				messageType: "EVENT",
				explicitMapping: ["issueInvitation", "dismissInvitation", "addWorkGroup"]
			}
		);
		couplingOptions.adapter.coupleObject(
			"user" + Skt.user.id + "-" + couplingOptions.carriedId, 
			this,
			{
				messageType: "EVENT",
				explicitMapping: ["addNoteGroup"]
			}
		);
	}

});